package cn.taketoday.live.thread;

import org.apache.commons.lang3.StringUtils;

import cn.taketoday.live.config.GlobalData;
import cn.taketoday.live.data.enums.AdvertStatus;
import cn.taketoday.live.handler.BarrageHandler;

/**
 * @author BanqiJane
 */
public class AdvertThread extends Thread {
  //	@SuppressWarnings("unused")
//	private Logger LOGGER = LogManager.getLogger(AdvertThread.class);
  public volatile boolean FLAG = false;
  private Short time;
  private String advertBarrage;
  private AdvertStatus advertStatus;

  @Override
  public void run() {
    // TODO 自动生成的方法存根
    super.run();
    String strings[] = null;
    while (!FLAG) {
      if (FLAG) {
        return;
      }
      if (GlobalData.webSocketProxy != null && !GlobalData.webSocketProxy.isOpen()) {
        return;
      }
      if (StringUtils.indexOf(getAdvertBarrage(), "\n") != -1) {
        strings = StringUtils.split(getAdvertBarrage(), "\n");

        if (getAdvertStatus() == AdvertStatus.DEFAULT) {
          // 顺序发
          for (String string : strings) {
            try {
              Thread.sleep(getTime() * 1000);
            }
            catch (InterruptedException e) {
//							LOGGER.debug("广告姬线程关闭:" + e);
            }
            BarrageHandler.send(string);
          }
        }
        else {
          // 随机发
          try {
            Thread.sleep(getTime() * 1000);
          }
          catch (InterruptedException e) {
          }
          int strLength = strings.length;
          if (strLength > 1) {
            int randomNum = (int) Math.ceil(Math.random() * strLength);
            BarrageHandler.send(strings[randomNum - 1]);
          }
          else {
            BarrageHandler.send(getAdvertBarrage());
          }

        }

      }
      else {
        try {
          Thread.sleep(getTime() * 1000);
        }
        catch (InterruptedException e) {

//					LOGGER.debug("广告姬线程关闭:" + e);
        }
        BarrageHandler.send(getAdvertBarrage());
      }
      try {
        Thread.sleep(10);
      }
      catch (InterruptedException e) {

//				LOGGER.debug("广告姬线程关闭:" + e);
      }

    }
  }

  public Short getTime() {
    return time;
  }

  public void setTime(Short time) {
    this.time = time;
  }

  public String getAdvertBarrage() {
    return advertBarrage;
  }

  public void setAdvertBarrage(String advertBarrage) {
    this.advertBarrage = advertBarrage;
  }

  public AdvertStatus getAdvertStatus() {
    return advertStatus;
  }

  public void setAdvertStatus(AdvertStatus advertStatus) {
    this.advertStatus = advertStatus;
  }

}
